<?php
// +----------------------------------------------------------------------
// | YUEGONGBAO [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.yuegongbaofund.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use think\Db;

class AdminBaseController extends BaseController
{
	public $user = null;

    public function _initialize()
    {
        // 监听admin_init
        hook('admin_init');
        parent::_initialize();
        $session_admin_id = session('ADMIN_ID');
        if (!empty($session_admin_id)) {
            $this->user = $user = Db::name('user')->where(['id' => $session_admin_id])->find();

            if (!$this->checkAccess($session_admin_id)) {
                $this->error("您没有访问权限！");
            }
            $this->assign("admin", $user);
        } else {
            if ($this->request->isPost()) {
                $this->error("您还没有登录！", url("admin/public/login"));
            } else {
                header("Location:" . url("admin/public/login"));
                exit();
            }
        }
		
		switch(strtolower($this->action)) {
			case 'admin/setting/sitepost':
				$this->log($this->user, '修改了站点设置');
				break;
			case 'admin/slide/addpost':
				$this->log($this->user, '添加了幻灯片组');
				break;
			case 'admin/slideitem/addpost':
				$this->log($this->user, '添加了幻灯片');
				break;
			case 'admin/slide/editpost':
				$this->log($this->user, '修改了幻灯片组');
				break;
			case 'admin/slideitem/editpost':
				$this->log($this->user, '修改了幻灯片');
				break;
			case 'admin/link/addpost':
				$this->log($this->user, '添加了友情链接');
				break;
			case 'admin/link/editpost':
				$this->log($this->user, '修改了友情链接');
				break;
			case 'admin/route/addpost':
				$this->log($this->user, '添加了路由规则');
				break;
			case 'admin/route/editpost':
				$this->log($this->user, '修改了路由规则');
				break;
			case 'admin/setting/uploadpost':
				$this->log($this->user, '修改了上传设置');
				break;
			case 'admin/rbac/roleaddpost':
				$this->log($this->user, '添加了管理员');
				break;
			case 'admin/rbac/roleeditpost':
				$this->log($this->user, '修改了管理员信息');
				break;
			case 'portal/adminarticle/addpost':
				$log = '添加了新闻';
				switch($this->request->post('post.post_type/d')) {
					case 5:
						$log = '添加了楼盘信息';
						break;
					case 4:
						$log = '添加了下载文档';
						break;
					case 3:
						$log = '添加了视频';
						break;
				}
				$this->log($this->user, $log);
				break;
			case 'portal/adminarticle/editpost':
				$log = '修改了内容';
				switch($this->request->post('post.post_type/d')) {
					case 5:
						$log = '修改了楼盘信息';
						break;
					case 4:
						$log = '修改了下载文档';
						break;
					case 3:
						$log = '修改了视频';
						break;
				}
				$this->log($this->user, $log);
				break;
			case 'portal/admincategory/addpost':
				$this->log($this->user, '添加了文章分类');
				break;
			case 'portal/admincategory/editpost':
				$this->log($this->user, '修改了文章分类');
				break;	
			case 'portal/adminpage/addpost':
				$this->log($this->user, '添加了页面');
				break;
			case 'portal/adminpage/editpost':
				$this->log($this->user, '修改了页面');
				break;	
			case 'portal/admintag/addpost':
				$this->log($this->user, '添加了标签');
				break;
			case 'portal/admintag/editpost':
				$this->log($this->user, '修改了标签');
				break;	
		}
		
    }
	
	// 记录日志
	public function log($admin, $content, $data = '') {
		$data = [
			'action'	=> $this->action,
			'content'	=> '['.$admin['user_login'].'] '.$content,
			'note'		=> $data,
			'admin_id'	=> $admin['id'],
			'user_login'=> $admin['user_login'],
			'ip'		=> $ip = get_client_ip(0, true), 
			'create_time'	=> time(),
		];
		
		Db::name('admin_log')->insert($data);
	}

    public function _initializeView()
    {
        $cmfAdminThemePath    = config('cmf_admin_theme_path');
        $cmfAdminDefaultTheme = config('cmf_admin_default_theme');

        $themePath = "{$cmfAdminThemePath}{$cmfAdminDefaultTheme}";

        $root = cmf_get_root();

        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "$themePath/");
        config('view_replace_str', $viewReplaceStr);
    }

    /**
     * 初始化后台菜单
     */
    public function initMenu()
    {
    }

    /**
     *  检查后台用户访问权限
     * @param int $userId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($userId)
    {
        // 如果用户id是1，则无需判断
        if ($userId == 1) {
            return true;
        }

        $module     = $this->request->module();
        $controller = $this->request->controller();
        $action     = $this->request->action();
        $rule       = $module . $controller . $action;

        $notRequire = ["adminIndexindex", "adminMainindex"];
        if (!in_array($rule, $notRequire)) {
            return cmf_auth_check($userId);
        } else {
            return true;
        }
    }

}